#include "es_drv.h"

ES_STATIC es_drv_t *es_drv_list = NULL;

/**
 * @brief 根据设备描述符查找设备驱动
 *
 * @param fd 设备号
 *
 * @return 设备结构体指针
 */
es_drv_t *es_drv_find(ES_INT32 fd)
{
	ES_ASSERT(fd > 0);

    es_drv_t* cur = es_drv_list;

    while( cur != NULL )
    {
        if(cur->id == fd)
        {
            return cur;
        }
        cur = cur->next;
    }
    return NULL;
}

/**
 * @brief 判断设备驱动是否存在
 *
 * @param fd 设备号
 *
 * @return ES_TRUE  设备存在
 * 		   ES_FALSE 设备不存在
 */
bool es_drv_is_exists(ES_INT32 fd)
{
	ES_ASSERT(fd > 0);

    es_drv_t *drv = es_drv_find(fd);

    if(drv != NULL)
        return ES_TRUE;
    else
        return ES_FALSE;
}

/**
 * @brief 向设备列表中插入设备
 *
 * @param drv 设备结构体指针
 *
 * @return ES_TRUE 插入成功
 */
ES_INT32 es_drv_list_inster(es_drv_t *drv)
{
	ES_ASSERT(drv != NULL);

    es_drv_t *cur = es_drv_list;

    if(NULL == es_drv_list)
    {
        es_drv_list = drv;
        drv->next   = NULL;
    }
    else
    {
        while(NULL != cur->next)
        {
            cur = cur->next;
        }
        cur->next = drv;
        drv->next = NULL;
    }
    return ES_TRUE;
}

/**
 * @brief 注册设备
 *
 * @param drv 设备结构体指针
 *
 * @return ES_TRUE  注册成功
 * @return ES_FALSE 注册失败
 */
ES_INT32 es_drv_register(es_drv_t *drv)
{
    if((NULL == drv) || (es_drv_is_exists(drv->id)))
    {
        return ES_FALSE;
    }
    if((0 >= drv->id) ||  (NULL == drv->drv_ops))
    {
        return ES_FALSE;
    }
    return es_drv_list_inster(drv);
}
